<?php
namespace App\Http\Service;

use GuzzleHttp\Client;
use Illuminate\Support\Str;
use Illuminate\Support\Facades\Log;
use App\Http\Service\BaseService;


class TaobaoService extends BaseService
{
    protected $client;
    protected $baseUrl = 'https://eco.taobao.com/router/rest';

    public function __construct()
    {
        $this->client = new Client([
            'timeout' => 15,
            'headers' => ['Content-Type' => 'application/x-www-form-urlencoded']
        ]);
    }

    /**
     * 生成签名
     */
    protected function generateSign(array $params, string $secret): string
    {
        ksort($params);
        $stringToSign = $secret;
        foreach ($params as $k => $v) {
            $stringToSign .= "$k$v";
        }
        $stringToSign .= $secret;
        return strtoupper(md5($stringToSign));
    }

    /**
     * 发送API请求
     */
    protected function sendRequest(string $method, array $apiParams, ?string $session = null): array
    {
        $commonParams = [
            'method' => $method,
            'app_key' => config('services.taobao.app_key'),
            'timestamp' => now()->format('Y-m-d H:i:s'),
            'format' => 'json',
            'v' => '2.0',
            'sign_method' => 'md5',
        ];

        if ($session) {
            $commonParams['session'] = $session;
        }

        $params = array_merge($commonParams, $apiParams);
        //dd($params);
        $params['sign'] = $this->generateSign($params, config('services.taobao.app_secret'));

        try {
            $response = $this->client->post($this->baseUrl, ['form_params' => $params]);
            return json_decode($response->getBody(), true);
        } catch (\Exception $e) {
            Log::error('Taobao API Error: '.$e->getMessage());
            return ['error' => $e->getMessage()];
        }
    }

    //1. 订单查询 taobao.tbk.sc.order.details.get
    public function getScOrders(string $startTime,string $endTime,int $queryType,?string $session,int $pageNo = 1,int $pageSize = 20,?int $tkStatus = null): array 
    {
        // 验证时间跨度 ≤24小时
        if (strtotime($endTime) - strtotime($startTime) > 86400) {
            throw new \InvalidArgumentException('时间跨度不能超过24小时');
        }

        $params = [
            'start_time' => $startTime,
            'end_time' => $endTime,
            'query_type' => $queryType,
            'page_no' => $pageNo,
            'page_size' => $pageSize,
        ];

        if ($tkStatus) {
            $params['tk_status'] = $tkStatus;
        }

        return $this->sendRequest('taobao.tbk.sc.order.details.get', $params, $session);
    }

    // 维权订单查询 taobao.tbk.sc.relation.refund
    public function getRefundOrders(string $searchOption,?string $session,int $pageNo = 1,int $pageSize = 20,?string $bizType = null): array 
    {
        $params = [
            'search_option' => $searchOption, // JSON格式查询条件
            'page_no' => $pageNo,
            'page_size' => $pageSize,
        ];

        if ($bizType) {
            $params['biz_type'] = $bizType; // 业务类型：1-维权 2-退款
        }

        return $this->sendRequest('taobao.tbk.sc.relation.refund', $params, $session);
    }
    // 成员组管理 taobao.tbk.sc.membergroup.optional   // add/delete
    public function manageMemberGroup(string $operation,string $groupName,array $memberIds,?string $session): array 
    {
        $params = [
            'group_name' => $groupName,
            'member_list' => json_encode(array_map('intval', $memberIds)),
            'opt_type' => $operation === 'add' ? 1 : 2,
        ];

        return $this->sendRequest('taobao.tbk.sc.membergroup.optional', $params, $session);
    }

    // 获取授权URL
    public function authRedirect()
    {
        $params = [
            'response_type' => 'code',
            'client_id' => config('services.taobao.app_key'),
            'redirect_uri' => route('taobao.callback'),
            'state' => Str::random(16),
            'view' => 'web' // 移动端用'm'
        ];

        $url = 'https://oauth.taobao.com/authorize?' . http_build_query($params);
        return redirect($url);
    }

    // 回调处理
    public function handleCallback(Request $request)
    {
        $code = $request->input('code');
        $response = $this->client->post('https://oauth.taobao.com/token', [
            'form_params' => [
                'grant_type' => 'authorization_code',
                'client_id' => config('services.taobao.app_key'),
                'client_secret' => config('services.taobao.app_secret'),
                'code' => $code,
                'redirect_uri' => route('taobao.callback')
            ]
        ]);

        $data = json_decode($response->getBody(), true);
        // 保存 $data['access_token'] 到用户记录
    }

}
